package com.stylefeng.guns.modular.train.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.MvcResult;
import com.stylefeng.guns.common.persistence.model.ContestRule;
import com.stylefeng.guns.common.persistence.model.Dict;
import com.stylefeng.guns.common.persistence.model.Employee;
import com.stylefeng.guns.config.excel.ExcelExportStylerImpl;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.modular.system.service.IContestRuleService;
import com.stylefeng.guns.modular.system.service.IDictService;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import com.stylefeng.guns.modular.train.service.impl.ContestPointsServiceImpl;
import com.stylefeng.guns.modular.train.transfer.EmpPointsDto;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.boot.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.common.persistence.model.ContestPoints;
import com.stylefeng.guns.modular.train.service.IContestPointsService;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.stylefeng.guns.common.constant.Const;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * ContestPoints控制器
 *
 * @author fengshuonan
 * @Date 2018-01-11 23:34:34
 */
@Controller
@RequestMapping("/contestPoints")
public class ContestPointsController extends BaseController {

    private String PREFIX = "/train/contestPoints/";

    @Autowired
    private IContestPointsService contestPointsService;

    @Autowired
    private IContestRuleService contestRuleService;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDictService dictService;

    private static List<ContestPoints> REPEAT = new ArrayList<>();
    /**
     * 跳转到ContestPoints首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "contestPoints.html";
    }

    /**
     * 跳转到添加ContestPoints
     */
    @RequestMapping("/contestPoints_add")
    public String contestPointsAdd(Model model) {
        List<ContestRule> companyLists = getCompanyRuleList();
        model.addAttribute("companyLists",companyLists);
        model.addAttribute("companyLevel",companyLists.get(0).getCompanyLevel());
        return PREFIX + "contestPoints_add.html";
    }


    /**
     * 跳转到修改ContestPoints
     */
    @RequestMapping("/contestPoints_update/{contestPointsId}")
    public String contestPointsUpdate(@PathVariable String contestPointsId, Model model) {
        ContestPoints contestPoints = contestPointsService.selectById(contestPointsId);

        List<ContestRule> contestRules = contestRuleService.getContestRules(contestPoints.getCompanyTypeCode());
        List<ContestRule> winRules = contestRuleService.getWinRules(contestPoints.getCompanyTypeCode(), contestPoints.getContestTypeCode());

        model.addAttribute("companyLists",getCompanyRuleList());
        model.addAttribute("contestRules",contestRules);
        model.addAttribute("winRules",winRules);


        model.addAttribute("item",contestPoints);
        LogObjectHolder.me().set(contestPoints);
        return PREFIX + "contestPoints_edit.html";
    }

    /**
     * 获取ContestPoints列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee, Double min, Double max) {
        if(BeanUtils.checkFieldValueNull(employee) && min == null && max == null){
            return contestPointsService.selectList(null);
        }

        EntityWrapper<Employee> wrapper = new EntityWrapper<>();
        wrapper.setEntity(employee);
        List<Employee> employees = employeeService.selectList(wrapper);
        Set<String> empCodes = new HashSet<>();
        employees.forEach(e -> empCodes.add(e.getEmpCode()));

        List<ContestPoints> networkTrainPointss = new ArrayList<>();
        if(!empCodes.isEmpty()){
            EntityWrapper<ContestPoints> nwWrapper = new EntityWrapper<>();
            nwWrapper.in("emp_code",empCodes);

            if(min != null || max != null){
                min = min == null ? 0.0 : min;
                max = max == null ? 9999.0 : max;

                nwWrapper.between("integral",min,max);
            }
            networkTrainPointss = contestPointsService.selectList(nwWrapper);
        }

        return networkTrainPointss;
    }

    /**
     * 新增ContestPoints
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(ContestPoints contestPoints) {
        contestPoints.setCreateDate(new Date());
        contestPoints.setDataOrigin(Const.IMPORT_TYPE_SYS);
        contestPointsService.insert(contestPoints);
        return super.SUCCESS_TIP;
    }

    @RequestMapping(value = "/adds")
    @ResponseBody
    public Object adds(@RequestBody ContestPoints[] repeatData) {
//        List<ContestPoints> contestPoints = JSONArray.parseArray(repeatData, ContestPoints.class);
        Map<String, List<Dict>> dictMap = new HashMap<>();
        dictMap.put(Const.DICT_COMPANY_TYPE, dictService.getChildByCode(Const.DICT_COMPANY_TYPE));
        dictMap.put(Const.DICT_CONTEST_TYPE, dictService.getChildByCode(Const.DICT_CONTEST_TYPE));
        dictMap.put(Const.DICT_WIN_TYPE, dictService.getChildByCode(Const.DICT_WIN_TYPE));

        for (ContestPoints contestPoint : repeatData) {
            contestPoint.setCreateDate(new Date());
            contestPoint.setDataOrigin(Const.IMPORT_TYPE_SYS);
            contestRuleService.calIntegral(contestPoint,dictMap);
            contestPointsService.insert(contestPoint);
        }

        return super.SUCCESS_TIP;
    }

    /**
     * 删除ContestPoints
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String contestPointsId) {
        if(contestPointsId.contains(",")){
            List<String> ids = Arrays.asList(contestPointsId.split(","));
            contestPointsService.deleteBatchIds(ids);
        }else{
            contestPointsService.deleteById(contestPointsId);
        }

        return SUCCESS_TIP;
    }

    /**
     * 修改ContestPoints
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(ContestPoints contestPoints) {
        contestPointsService.updateById(contestPoints);
        return super.SUCCESS_TIP;
    }

    /**
     * ContestPoints详情
     */
    @RequestMapping(value = "/detail/{contestPointsId}")
    @ResponseBody
    public Object detail(@PathVariable("contestPointsId") String contestPointsId) {
        return contestPointsService.selectById(contestPointsId);
    }


    /**
     * 跳转到导入ContestPoints
     */
    @RequestMapping("/contestPoints_import")
    public String contestPointsImport() {
        return PREFIX + "contestPoints_import.html";
    }



    /**
     * 导入ContestPoints
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) {

        ImportParams params = new ImportParams();
        params.setStartRows(0);
        params.setTitleRows(1);
        int count = 2;
        try {
            List<ContestPoints> contestPointss = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), ContestPoints.class, params);
            Date now = new Date();

            Map<String, List<Dict>> dictMap = new HashMap<>();
            dictMap.put(Const.DICT_COMPANY_TYPE, dictService.getChildByCode(Const.DICT_COMPANY_TYPE));
            dictMap.put(Const.DICT_CONTEST_TYPE, dictService.getChildByCode(Const.DICT_CONTEST_TYPE));
            dictMap.put(Const.DICT_WIN_TYPE, dictService.getChildByCode(Const.DICT_WIN_TYPE));

            Map<String, String> nameAndCode = employeeService.getNameAndCode();

            List<ContestPoints> noRepeat = new ArrayList<>();
            List<ContestPoints> hasNameList = new ArrayList<>();

            for (ContestPoints contestPoints : contestPointss) {
                
                contestPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
                contestPoints.setCreateDate(now);

                //姓名检测
                if(StringUtils.isEmpty(contestPoints.getEmpCode())){
                    if(nameAndCode.containsKey(contestPoints.getEmpName())){
                        //有该姓名，检测是否重名
                        if(nameAndCode.get(contestPoints.getEmpName()).contains(",")){
                            //有重名情况
                            contestPoints.setEmpCode(Const.DEFAULT_CODE);
                            REPEAT.add(contestPoints);
                        }else{
                            //无重名、正常插入
                            contestPoints.setEmpCode(nameAndCode.get(contestPoints.getEmpName()));
                            contestRuleService.calIntegral(contestPoints,dictMap);
                            noRepeat.add(contestPoints);
                        }
                    }else{
                        throw new Exception("姓名为 "+ contestPoints.getEmpName() + " 在员工管理中不存在!");
                    }
                }else{
                    contestRuleService.calIntegral(contestPoints,dictMap);
                    hasNameList.add(contestPoints);
                }

                count++;
            }

            if(noRepeat.size() > 0){
                contestPointsService.insertBatch(noRepeat);
            }
            if(hasNameList.size() > 0){
                contestPointsService.insertBatch(hasNameList);
            }
            if(!REPEAT.isEmpty()){
                MvcResult mvcResult = new MvcResult();
                mvcResult.setData(REPEAT);
                return mvcResult;
            }

        } catch (Exception e) {
            return new ErrorTip(400,"第"+ count+"条 " +e.getMessage());
        }
        SuccessTip successTip = super.SUCCESS_TIP;
        successTip.setMessage(String.format("成功插入%d", count-2)  + "条数据");
        return successTip;
    }

    /**
     * 导出
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            List<ContestPoints> contestPoints= contestPointsService.selectList(null);
            ExportParams exportParams=new ExportParams("竞赛调考积分统计表", "竞赛调考积分统计表");
            exportParams.setStyle(ExcelExportStylerImpl.class);
            exportParams.setTitleHeight((short)14);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ContestPoints.class, contestPoints);
            OutputStream outputStream=response.getOutputStream();
                String fileName="竞赛调考积分统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
//            throw new Exception("");
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/repeat")
    public String repeat(Model model){
        model.addAttribute("repeat", JSON.toJSONString(REPEAT));

        //消费后清空
        REPEAT = new ArrayList<>();
        return PREFIX + "repeat.html";
    }

    /**
     * 获取积分规则
     * @return
     */
    private List<ContestRule> getCompanyRuleList(){
        //获取设置了规则关系的公司
        List<ContestRule> contestRules =  contestRuleService.selectByMap(new HashMap<>());
        List<ContestRule> companyLists = new ArrayList<>();
        Set<String> companyLevelCodes = new HashSet<>();
        for (ContestRule contestRule : contestRules) {
            String companyLevelCode = contestRule.getCompanyLevelCode();
            if(!companyLevelCodes.contains(companyLevelCode)){
                companyLevelCodes.add(companyLevelCode);
                companyLists.add(contestRule);
            }
        }
        return companyLists;
    }
}
